<template>
    <div class="page-form page-act-add">
      <Form  ref="formValidate" :model="formItem" :rules="ruleValidate" :label-width="120">
          <FormItem prop="msg" label="消息：">
              <Input v-model="formItem.msg" placeholder="请输入消息内容"></Input>
          </FormItem>         
          <FormItem>
              <Button type="primary" @click="handleSubmit('formValidate')">提交</Button>
              <Button type="ghost" @click="handleReset('formValidate')" style="margin-left: 8px">重置</Button>
          </FormItem>
      </Form>
    </div>
</template>
<style scoped lang="less">
.page-form {
  overflow: auto;
  box-sizing: border-box;
  padding: 15px 0 0 0;
}
</style>
<script>
const socket = require("socket.io-client")("http://127.0.0.1:7001", {
  // 实际使用中可以在这里传递参数
  query: {
    userId: `client_${Math.random()}`
  }
});
export default {
  data() {
    return {
      id: "",
      formItem: {
        msg: ""
      },
      ruleValidate: {
        msg: [
          {
            required: true,
            message: "请输入消息内容~",
            trigger: "blur"
          }
        ]
      }
    };
  },
  mounted() {
    "use strict";

    socket.on("connect", () => {
      // socket 建立连接之后，往服务端发送客户端信息
      // { id,name}
      var user = {
        id: parseInt(Math.random() * 100000),
        name: "mc" + parseInt(Math.random() * 1000)
      };
      socket.emit("chat", user);
    });

    socket.on("res", msg => {
      console.log("res from server: %s!", msg);
    });
    socket.on("login", msg => {
      console.log(msg.name + "进入聊天室");
    });
    //监听用户退出
    socket.on("logout", msg => {
      console.log(msg.name + "退出聊天室");
    });
  },
  methods: {
    handleSubmit(name) {
      var self = this;
      this.$refs[name].validate(valid => {
        console.log("----");
        socket.emit("res", self.formItem.msg);
      });
    },
    handleReset(name) {
      this.$refs[name].resetFields();
    }
  }
};
</script>
